package com.sany.canwifi.udp;

import android.util.Log;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * author : dingqb
 * e-mail : dingqb@sany.com.cn
 * date   : 2022/1/4 4:23 PM
 * desc   :
 * version: 1.0
 */
public class ReveiverUdp {
    public static final String TAG = "ReveiverUdp";

    public void start() {
        Log.e(TAG, "start: ");
        try {
            receive();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
    }

    public void receive() throws Exception {
        Log.e(TAG, "receive: ");
        // 定义一个接收端，并且指定了接收的端口号
        DatagramSocket socket = new DatagramSocket(5000);
        while (true) {
            System.out.println();
            byte[] buf = new byte[1024];
            // 解析数据包
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            String ip = packet.getAddress().getHostAddress();
            System.out.println("收到 ip==" + ip);
            socket.receive(packet);

            buf = packet.getData();

            String data = new String(buf, 0, packet.getLength());
//            System.out.println("收到 " + ip + " 发来的消息：" + data);

            Thread.sleep(200);

        }

    }
}
